<?php

/**
 * This is the model class for table "{{posts}}".
 *
 * The followings are the available columns in table '{{posts}}':
 * @property string $post_id
 * @property string $user_id
 * @property string $post_content
 * @property string $post_title
 * @property string $post_excerpt
 * @property string $post_status
 * @property string $comment_status
 * @property string $ping_status
 * @property string $post_password
 * @property string $post_name
 * @property string $to_ping
 * @property string $pinged
 * @property string $post_content_filtered
 * @property string $post_parent
 * @property string $guid
 * @property integer $menu_order
 * @property string $post_type
 * @property string $post_mime_type
 * @property string $comment_count
 * @property integer $created
 * @property integer $modified
 */
class Posts extends CActiveRecord {
    private $_oldTags;
    public $_oldCates;
    /**
     * Returns the static model of the specified AR class.
     * @return Posts the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{posts}}';
    }

    /**
     * add default created modified time
     */

    public function behaviors() {
        return array(
                'AutoTimestampBehavior' => array(
                        'class' => 'application.components.AutoTimestampBehavior',
                //You can optionally set the field name options here
                )
        );
    }
    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
                array('post_content, post_cates, post_title ', 'required'),
                array('menu_order', 'numerical', 'integerOnly'=>true),
                array('user_id, post_status, comment_status, ping_status, post_password, post_parent, post_type, comment_count', 'length', 'max'=>20),
                array('post_name', 'length', 'max'=>200),
                array('tags','safe'),
                array('guid', 'length', 'max'=>255),
                array('post_mime_type', 'length', 'max'=>100),
                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('post_id, user_id, post_content, post_title, post_excerpt, post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_content_filtered, post_parent, guid, menu_order, post_type, post_mime_type, comment_count, created, modified', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
                'author' => array(self::BELONGS_TO, 'Users', 'user_id'),
                'cate' => array(self::MANY_MANY,'Category','{{cate_post}}(post_id, cate_id)'),
                'comments' => array(self::HAS_MANY, 'Comment', 'comment_post_id', 'condition'=>'comments.comment_status='.Comment::STATUS_APPROVED, 'order'=>'comments.created DESC'),
                'commentCount' => array(self::STAT, 'Comment', 'comment_post_id', 'condition'=>'comment_status='.Comment::STATUS_APPROVED),
        );
    }

    /**
     * add default desc
     */

    public function scopes() {
        return array(
                'published'=>array(
                        'order'=>'created desc',
                ),
        );

    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
                'post_id' => Yii::t('model','Posts Post'),
                'user_id' => Yii::t('model','Posts User'),
                'post_cates' => Yii::t('model','Posts Post Cates'),
                'post_content' => Yii::t('model','Posts Post Content'),
                'post_title' => Yii::t('model','Posts Post Title'),
                'post_excerpt' => Yii::t('model','Posts Post Excerpt'),
                'post_status' => Yii::t('model','Posts Post Status'),
                'comment_status' => Yii::t('model','Posts Comment Status'),
                'ping_status' => Yii::t('model','Posts Ping Status'),
                'post_password' => Yii::t('model','Posts Post Password'),
                'post_name' => Yii::t('model','Posts Post Name'),
                'to_ping' => Yii::t('model','Posts To Ping'),
                'pinged' => Yii::t('model','Posts Pinged'),
                'post_content_filtered' => Yii::t('model','Posts Post Content Filtered'),
                'tags' => Yii::t('model','Posts Tags'),
                'post_parent' => Yii::t('model','Posts Post Parent'),
                'guid' => Yii::t('model','Posts Guid'),
                'menu_order' => Yii::t('model','Posts Menu Order'),
                'post_type' => Yii::t('model','Posts Post Type'),
                'post_mime_type' => Yii::t('model','Posts Post Mime Type'),
                'post_views' => Yii::t('model','Posts Post Views'),
                'comment_count' => Yii::t('model','Posts Comment Count'),
                'created' => Yii::t('model','Posts Created'),
                'modified' => Yii::t('model','Posts Modified'),
        );
    }

    public function getUrl() {
        return url('post/view', array(
                'id'=>$this->post_id,
                'title'=>$this->post_title,
        ));
    }

    public function getCatename() {
        if(strpos($this->post_cates,',')) {
            return "22";
        }else
            return "1";
    }

    public function getDesction() {
        if($this->post_status=='publish') {
            if($this->post_password) {
                return '<form method="post" action='.url('post/pass',array('id'=>$this->post_id)).'>
<p>这是一篇受密码保护的文章。您需要提供访问密码：</p>
<p><label for="pwbox-4">密码：
<input type="password" size="20" id="pwbox-4" name="post_password">
<input type="hidden" size="20" id="pwbox-4" name="post_id" value='.$this->post_id.'></label>
<input type="submit" value="提交" name="Submit"></p></form>';
            }else {
                return empty($this->post_excerpt)?$this->post_content:$this->post_excerpt;
            }
        }else {
            return empty($this->post_excerpt)?$this->post_content:$this->post_excerpt;
        }
    }

    public function getBody() {
        if($this->post_status=='publish') {
            if($this->post_password) {
                return '<form method="post" action='.url('post/pass',array('id'=>$this->post_id)).'>
<p>这是一篇受密码保护的文章。您需要提供访问密码：</p>
<p><label for="pwbox-4">密码：
<input type="password" size="20" id="pwbox-4" name="post_password">
<input type="hidden" size="20" id="pwbox-4" name="post_id" value='.$this->post_id.'></label>
<input type="submit" value="提交" name="Submit"></p></form>';
            }else {
                return $this->post_content;
            }
        }else {
            return $this->post_content;
        }
    }


    public function getLink() {
        if($this->post_status=='publish') {
            if(!$this->post_password) {
                return CHtml::link(CHtml::encode($this->post_title), array('post/view', 'id'=>$this->post_id,'title'=>$this->post_title));
            }else {
                return CHtml::link("密码保护：".CHtml::encode($this->post_title), array('post/view', 'id'=>$this->post_id,'title'=>$this->post_title));
            }
        }else {
            return CHtml::link("私有文章：".CHtml::encode($this->post_title), array('post/view', 'id'=>$this->post_id,'title'=>$this->post_title));
        }
    }
    /**
     * @return array a list of links that point to the post list filtered by every tag of this post
     */
    public function getTagLinks() {
        $links=array();
        foreach(Tag::string2array($this->tags) as $tag)
            $links[]=CHtml::link(CHtml::encode($tag), array('index/index', 'tag'=>$tag));
        return $links;
    }

    /**
     * @return array a list of links that point to the post list filtered by every tag of this post
     */
    public function getCateLinks() {
        $links=array();
        foreach($this->cate as $cate)
            $links[]=CHtml::link(CHtml::encode($cate->name), array('category/index', 'id'=>$cate->category_id));
        return $links;
    }

    /**
     * Normalizes the user-entered tags.
     */
    public function normalizeTags($attribute,$params) {
        $this->tags=Tag::array2string(array_unique(Tag::string2array($this->tags)));
    }

    /**
     * This is invoked when a record is populated with data from a find() call.
     */
    protected function afterFind() {
        parent::afterFind();
        $this->_oldTags=$this->tags;
        $this->_oldCates=$this->post_cates;
    }

    /**
     * This is invoked before the record is saved.
     * @return boolean whether the record should be saved.
     */
    protected function beforeSave() {
        if(parent::beforeSave()) {
            if($this->isNewRecord) {
                //$this->user_id=Yii::app()->user->id;
            }
            return true;
        }
        else
            return false;
    }

    /**
     * This is invoked after the record is saved.
     */
    protected function afterSave() {
        parent::afterSave();
        Tag::model()->updateFrequency($this->_oldTags, $this->tags);
        Category::CateCount($this->post_cates);
        CatePost::model()->updateCates($this->_oldCates,$this->post_cates,$this->post_id);
    }

    /**
     * This is invoked after the record is deleted.
     */
    protected function afterDelete() {
        parent::afterDelete();
        Comment::model()->deleteAll('comment_post_id='.$this->post_id);
        Tag::model()->updateFrequency($this->tags, '');
    }


    /**
     * Adds a new comment to this post.
     * This method will set status and post_id of the comment accordingly.
     * @param Comment the comment to be added
     * @return boolean whether the comment is saved successfully
     */
    public function addComment($comment) {
        if(Yii::app()->params['commentNeedApproval'])
            $comment->comment_status=Comment::STATUS_PENDING;
        else
            $comment->comment_status=Comment::STATUS_APPROVED;
        $comment->comment_author_ip =ip2long(CHttpRequest::getUserHostAddress());
        $comment->comment_post_id=$this->post_id;
        return $comment->save();
    }
    public function getRssPosts($nums = 25, $category_id = null) {

        $criteria = new CDbCriteria();
        $criteria->select = 'id, subject, category_id, topic_id, source, summary, content'
                . ', post_time, post_user, update_time, visit_nums, digg_nums, comment_nums';
        $criteria->condition = self::tableName() . '.isshow = :yes and ' . self::tableName() . '.isauth = :yes';
        $criteria->params = array('yes' => self::YES);
        $criteria->limit = $nums;
        $criteria->order = 'update_time desc, ' . $this->tableName() . '.id desc';

        if (!empty($category_id)) {
            $criteria->condition .= ' and category_id = :cid';
            $criteria->params['cid'] = $category_id;
        }
        if (!empty($topic_id)) {
            $criteria->condition .= ' and topic_id = :tid';
            $criteria->params['tid'] = $topic_id;
        }
        $data = Post::model()->with('topic', 'category')->findAll($criteria);
        return $data;
    }
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;
        $criteria->order="created desc";

        $criteria->compare('post_id',$this->post_id,true);
        $criteria->compare('user_id',$this->user_id,true);
        $criteria->compare('post_cates',$this->post_cates,true);
        $criteria->compare('post_content',$this->post_content,true);
        $criteria->compare('post_title',$this->post_title,true);
        $criteria->compare('post_excerpt',$this->post_excerpt,true);
        $criteria->compare('post_status',$this->post_status,true);
        $criteria->compare('comment_status',$this->comment_status,true);
        $criteria->compare('ping_status',$this->ping_status,true);
        $criteria->compare('post_password',$this->post_password,true);
        $criteria->compare('post_name',$this->post_name,true);
        $criteria->compare('to_ping',$this->to_ping,true);
        $criteria->compare('pinged',$this->pinged,true);
        $criteria->compare('post_content_filtered',$this->post_content_filtered,true);
        $criteria->compare('tags',$this->tags,true);
        $criteria->compare('post_parent',$this->post_parent,true);
        $criteria->compare('guid',$this->guid,true);
        $criteria->compare('menu_order',$this->menu_order);
        $criteria->compare('post_type',$this->post_type,true);
        $criteria->compare('post_mime_type',$this->post_mime_type,true);
        $criteria->compare('post_views',$this->post_views);
        $criteria->compare('comment_count',$this->comment_count,true);
        $criteria->compare('created',$this->created);
        $criteria->compare('modified',$this->modified);

        return new CActiveDataProvider(get_class($this), array(
                        'criteria'=>$criteria,
        ));
    }
}
